/*
 * �b 2004/5/19 �إ�
 *
 */
package jaoso.framework.util;

import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import org.xml.sax.SAXException;

import java.beans.IntrospectionException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import java.util.Collection;
import java.util.Iterator;

/**
 * @author edgeloner@ edgeloner@163.com
 * 
 *  
 */
public final class XMLUtils
{
    /**
     * DOCUMENT ME!
     */
    private static Log log = LogFactory.getLog(XMLUtils.class);

    /**
     * Creates a new XMLUtils object.
     */
    private XMLUtils()
    {
    }

    /**
     * DOCUMENT ME!
     * 
     * @param doc
     *            DOCUMENT ME!
     * 
     * @return DOCUMENT ME!
     */
    public static Element getRootElement(final Document doc)
    {
        return doc.getRootElement();
    }

    /**
     * DOCUMENT ME!
     * 
     * @param args
     *            DOCUMENT ME!
     */
    public static void main(final String[] args)
    {
        String path = XMLUtils.class.getResource("/log4j.properties").getPath();
        path = path.substring(1, path.length());

        //for linux or unix
        if (!path.substring(0, 1).equals("/")
                && !path.substring(1, 2).equals(":"))
        {
            path = "/" + path;
        }

        Document doc = read(path);
        Element root = getRootElement(doc);
        Element item;
        Element node;

        for (Iterator i = root.elementIterator(); i.hasNext();)
        {
            item = (Element) i.next();

            for (Iterator ii = item.elementIterator(); ii.hasNext();)
            {
                node = (Element) ii.next();
            }

            //end for
        }

        //end for
        item = root.addElement("protected-resource");
        item.addElement("box").addText("102");
        item.addElement("desc").addText("the three page");
        item.addElement("url").addText("three.do");

        //write(doc, path);
    }

    /**
     * DOCUMENT ME!
     * 
     * @param fileName
     *            DOCUMENT ME!
     * 
     * @return DOCUMENT ME!
     */
    public static Document read(final String fileName)
    {
        SAXReader reader = new SAXReader();
        Document document = null;

        try
        {
            document = reader.read(fileName);
        } catch (DocumentException e)
        {
            log.error(e.getMessage());
        }

        return document;
    }

    /**
     * DOCUMENT ME!
     * 
     * @param doc
     *            DOCUMENT ME!
     * @param path
     *            DOCUMENT ME!
     */
    public static void write(final Document doc, final String path)
    {
        /*
         * try{ FileWriter out = new FileWriter(path); doc.write(out); } catch
         * (IOException e){ log.error(e.getMessage()); }
         */
        try
        {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter output = new XMLWriter(new FileWriter(new File(path)),
                    format);
            output.write(doc);
            output.close();
        } catch (IOException e)
        {
            log.error(e.getMessage());
        }
    }

    /**
     * DOCUMENT ME!
     * 
     * @param beans
     *            DOCUMENT ME!
     * @param path
     *            DOCUMENT ME!
     */
    public static void write(final Collection beans, final String path)
    {
        java.io.File f = new java.io.File(path);

        if (!f.exists())
        {
            try
            {
                f.createNewFile();
            } catch (IOException e1)
            {
                log.error("create file error", e1);
            }
        }

        PrintWriter pw = null;

        try
        {
            Writer wr = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");

            //pw = new PrintWriter(new FileOutputStream(f));
            pw = new PrintWriter(wr);
        } catch (FileNotFoundException e)
        {
            log.error("file not found error", e);
        } catch (UnsupportedEncodingException e)
        {
            log.error("file encoding error", e);
        }

        pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
        pw.write("<!DOCTYPE acl-config SYSTEM \"acl-config.dtd\">\n");

        // Betwixt just writes out the bean as a fragment
        // So if we want well-formed xml, we need to add the prolog
        // Create a BeanWriter which writes to our prepared stream
        BeanWriter beanWriter = new BeanWriter(pw);

        // Configure betwixt
        // For more details see java docs or later in the main documentation
        beanWriter.getXMLIntrospector().setAttributesForPrimitives(false);

        //beanWriter.setWriteIDs(false);
        beanWriter.enablePrettyPrint();

        try
        {
            beanWriter.write("acl-config", beans);
            pw.close();
        } catch (IOException e)
        {
            log.error("write file error", e);
        } catch (SAXException e)
        {
            log.error("write file error", e);
        } catch (IntrospectionException e)
        {
            log.error("write file error", e);
        }
    }
}